package src.percolation;

import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import src.utils.Utils;

public class Pr8 {

	/*
	 * El objetivo de este ejericicio es calcular la distribucion
	 * del segundo momento de la distribucion, cerca del punto critico
	 * y verle el exponente.
	 */
	public static void main(String[] argvs) throws IOException{
		
		
		int large;

		double minProba;
		double maxProba;
		double increment;
		String outputName;
		
		try {
			large = new Integer(argvs[0]);
			minProba = new Double(argvs[1]);
			maxProba = new Double(argvs[2]);
			increment = new Double(argvs[3]);
			outputName = argvs[4];
			
			
		} catch (Exception e) {
			showUsage();
			return;
		}
		
		
		Random gen = new Random();
		
		double pc = 0.593; //habra que cambiarla
		
		Map<Double,Double> criticalResults = new TreeMap<Double, Double>();
		
		for(double probability = minProba; probability < maxProba; probability += increment){

			//podria agregar un validador segun arriba o abajo
			//de pc, que itere hasta que la red percole o no
			//segun sea lo correcto
			
			long seed = gen.nextLong();
			Red myRed = new Red(large,seed);
			myRed.createGrid(probability);
		
			double secondMoment = getSecondMoment(myRed.clusterHistogram(),large);
			//System.out.println((probability-minProba)*100/maxProba);
			criticalResults.put(probability, secondMoment);
		}
		
		Utils.printToFile(criticalResults,outputName);
		
	}
	
	
	public static double getSecondMoment(Map<Integer,Integer> histogram, int large){

		//normalizacion ad hoc para este metodo, no para la red y su histograma
		
		double secondMoment = 0;
		
		//do not count biggest n clusters
		int n = 3;
		for (int i=1; i<histogram.size()-n;i++){
			if(histogram.containsKey(i))
				secondMoment += histogram.get(i)*i*i;
		}
		
		
		return secondMoment / (large*large*1.0);
	}
	
	private static void showUsage() {
		System.out.println("Usage: ");
		
		System.out.println("<netSize> <minProba> <maxProba> <increment>\n");
		
		System.out.println("<netSize>: size of net.");
		System.out.println("<minProba>: minimum probability.");
		System.out.println("<maxProba>: maximum probability.");
		System.out.println("<increment>: increment between probabilities.");	
	}
	
	
}
